#! /usr/bin/python
import pygtk
pygtk.require("2.0")
import os
import sys
import btctl
import gtk
import gconf
import pycurl
import urllib

def progress_callback (bo, bdaddr):
    trayicon.set_blinking(1)
    print ("got progress from %s" % (bdaddr))

def request_put_callback (bo, bdaddr):
    print ("device %s wants to send a file" % (bdaddr))
    bo.set_response (True)

def put_callback (bo, bdaddr, fname, body, timestamp):
    print ("device %s sent a file" % (bdaddr))
    print "Filename %s, timestamp %d " % (fname, timestamp)
    f = open("/tmp" + os.sep + fname,'wb')
    f.write(body)
    f.close()
    print "File saved in /tmp" + os.sep + fname
    post_file(bdaddr, "/tmp" + os.sep + fname)
    trayicon.set_blinking(0)
    bo.set_response (True)

def error_callback (bo, bdaddr, err):
    print ("got error %d from %s" % (err, bdaddr))

def complete_callback (bo, bdaddr):
    print ("transfer complete from %s" % (bdaddr))

def post_file (sender, file):
    username = get_key(USER_KEY)
    password = get_key(PASS_KEY)
    url      = get_key(SERVER_KEY)
    
    ch = pycurl.Curl()
    ch.setopt(pycurl.URL, url)
    print "Post file to " + url
    post_fields = [
        ('file', (pycurl.FORM_FILE, file)),
        ('username', username),
        ('password', password),
        ('sender', sender)]
    ch.setopt(pycurl.HEADER, 1)
    ch.setopt(pycurl.POST, 1)
    ch.setopt(pycurl.HTTPPOST, post_fields)
    ch.perform()  

def popup_menu_callback (widget, button, time, data = None):
    if button == 3 and data:
        data.show_all()
        data.popup(None, None, None, 3, time)

def preferences_callback (widget, data = None):
    dialog = gtk.Dialog("Foovision preferences")
    h = gtk.HBox()
    h.set_border_width(6)
    h.set_spacing(6)
   

    # Labels
    v = gtk.VBox()
    v.set_spacing(6)

    l = gtk.Label("User:")
    v.pack_start(l, True, False, 0)

    l = gtk.Label("Password:")
    v.pack_start(l, True, False, 0)

    l = gtk.Label("Server:")
    v.pack_start(l, True, False, 0)

    h.pack_start(v, False, False, 0)

    # Entries
    v = gtk.VBox()
    v.set_spacing(6)

    user_entry = gtk.Entry()
    user_entry.set_width_chars(25)
    user_entry.set_text(get_key(USER_KEY))
    v.pack_start(user_entry, True, True, 0)

    pass_entry = gtk.Entry()
    pass_entry.set_width_chars(25)
    pass_entry.set_visibility(False)
    pass_entry.set_text(get_key(PASS_KEY))
    v.pack_start(pass_entry, True, True, 0)

    server_entry = gtk.Entry()
    server_entry.set_width_chars(25)
    server_entry.set_text(get_key(SERVER_KEY))
    v.pack_start(server_entry, True, True, 0)

    h.pack_start(v, True, True, 0)

    dialog.vbox.pack_start(h, False, False, 0)
    dialog.vbox.show_all()

    dialog.add_button (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
    dialog.add_button (gtk.STOCK_APPLY, gtk.RESPONSE_APPLY)
    dialog.connect("response", dialog_response_callback, user_entry, pass_entry, server_entry)
    dialog.run()
    dialog.destroy()

def dialog_response_callback(dialog, response, user, pwd, server):
    if (response == gtk.RESPONSE_APPLY):
        gconf_client.set_string(USER_KEY,   user.get_text())
        gconf_client.set_string(PASS_KEY,   pwd.get_text())
        gconf_client.set_string(SERVER_KEY, server.get_text())
        print "Saved preferences"
    else:
        print "Cancel"

def quit_callback (widget, data = None):
    if data:
       data.set_visible(False)
       gtk.main_quit()

def get_key (k):
    v = ""
    v = gconf_client.get_string(k)
    if (v == None):
        if (k == SERVER_KEY):
            v = "http://foovision.org/receiver"
        else:
            v = ""
        gconf_client.set_string(k, v)
    return v

# Constants
FOOVISION_PATH = "/apps/foovision"
USER_KEY   = FOOVISION_PATH + "/user"
PASS_KEY   = FOOVISION_PATH + "/password"
SERVER_KEY = FOOVISION_PATH + "/server"

# Obex 
bo = btctl.Obex()
bo.connect("progress", progress_callback);
bo.connect("request-put", request_put_callback);
bo.connect("put", put_callback);
bo.connect("error", error_callback);
bo.connect("complete", complete_callback);

if not bo.is_initialised():
    print ("Server not initialised")
    sys.exit (1)

# GConf client
gconf_client = gconf.client_get_default()

# Tray icon
trayicon = gtk.StatusIcon()
trayicon.set_from_file("foovision.png")

menu = gtk.Menu()
menuItem = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
menuItem.connect('activate', preferences_callback)
menu.append(menuItem)
menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
menuItem.connect('activate', quit_callback, trayicon)
menu.append(menuItem)


trayicon.connect('popup-menu', popup_menu_callback, menu)

print "pyfoovision running..."
gtk.main()
